import 'package:flutter/material.dart';
import 'package:chat_client/screens/home_screen.dart';
import 'package:chat_client/screens/auth/register_screen.dart';
import 'package:chat_client/services/auth_service.dart';
import 'package:chat_client/utils/validation.dart'; // 导入验证文件
import 'package:chat_client/widgets/c_popup_error.dart'; // 导入对话框文件

class LoginScreen extends StatefulWidget {
  const LoginScreen({super.key});

  @override
  LoginScreenState createState() => LoginScreenState();
}

class LoginScreenState extends State<LoginScreen> {
  final AuthService _authService = AuthService.instance;
  // 控制器
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _isLoading = false;

  // 登录方法
  Future<void> _login() async {
    final username = _usernameController.text.trim();
    final password = _passwordController.text.trim();

    setState(() {
      _isLoading = true;
    });

    // 校验用户名和密码
    if (!_validateInputs(username, password)) {
      setState(() {
        _isLoading = false;
      });
      return;
    }

    try {
      bool isLoggedIn = await _authService.login(username, password);
      if (isLoggedIn == true) {
        // 登录成功
        WidgetsBinding.instance.addPostFrameCallback((_) {
          Navigator.pushReplacement(
            context,
            MaterialPageRoute(builder: (context) => const HomeScreen()),
          );
        });
      } else {
        _showError('登录失败，请稍后重试');
      }
    } catch (e) {
      _showError(e.toString());
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 校验输入
  bool _validateInputs(String username, String password) {
    String? usernameError = Validator.validateUsername(username);
    if (usernameError != null) {
      _showError(usernameError);
      return false;
    }

    String? passwordError = Validator.validatePassword(password);
    if (passwordError != null) {
      _showError(passwordError);
      return false;
    }

    return true;
  }

  // 显示带动画的错误提示
  void _showError(String message) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return CustomErrorDialog(
          // 使用自定义的错误提示组件
          title: '登录失败',
          message: message,
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕宽度
    double width = MediaQuery.of(context).size.width;

    // 在 Web 平台时，设置宽度为 600（根据需求调整宽度），在手机和平板上使用默认宽度
    double formWidth = width > 500 ? 500 : width * 0.8;

    return Scaffold(
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Image.asset(
                  'assets/images/avatar01.jpg',
                  width: 150,
                  height: 150,
                  fit: BoxFit.cover,
                ),
                const SizedBox(height: 24),
                const Text(
                  'Login to Your Account',
                  style: TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 24),
                // 用户名输入框
                SizedBox(
                  width: formWidth,
                  child: TextField(
                    controller: _usernameController,
                    decoration: const InputDecoration(
                      labelText: '用户名',
                    ),
                  ),
                ),

                const SizedBox(height: 24),

                // 密码输入框
                SizedBox(
                  width: formWidth,
                  child: TextField(
                    controller: _passwordController,
                    obscureText: true,
                    decoration: const InputDecoration(labelText: '密码'),
                  ),
                ),
                const SizedBox(height: 24),

                // 忘记密码和注册账号按钮行
                SizedBox(
                  width: formWidth,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      // 注册账号按钮
                      TextButton(
                        onPressed: () {
                          // 注册账号操作
                          Navigator.push(
                            context,
                            MaterialPageRoute(
                                builder: (context) => const RegisterScreen()),
                          );
                        },
                        child: const Text('暂无账号？注册'),
                      ),
                      // 忘记密码按钮
                      TextButton(
                        onPressed: () {
                          // 忘记密码操作
                        },
                        child: const Text('忘记密码?'),
                      ),
                    ],
                  ),
                ),
                const SizedBox(height: 24),

                // 显示加载指示器或登录按钮
                _isLoading
                    ? const CircularProgressIndicator()
                    : SizedBox(
                        width: formWidth, // 按照相同的宽度限制按钮宽度
                        child: ElevatedButton(
                          onPressed: _login,
                          child: const Text('登录'),
                        ),
                      ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
